<template>
  <div class="my-course-container">
    <div class="header">
      <h2>我的班级管理</h2>
      <ElButton type="primary" @click="createClassDialogVisible = true" :icon="Plus">
        创建班级
      </ElButton>
    </div>

    <ElTable :data="classData" style="width: 100%" v-loading="loading">
<!--      <ElTableColumn prop="id" label="班级ID" width="80" />-->
      <ElTableColumn prop="className" label="班级名称" width="180" />
<!--      <ElTableColumn prop="majorId" label="专业ID" width="80" />-->
      <ElTableColumn prop="number" label="班级人数" width="180" />
<!--      <ElTableColumn prop="teacherId" label="教师ID" width="80" />-->
      <ElTableColumn label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <ElButton type="primary" size="small" @click="openScheduleDialog(row)">
            排课
          </ElButton>
          <ElButton type="danger" size="small" @click="deleteClass(row.id,row.className)">删除</ElButton>
        </template>

      </ElTableColumn>
    </ElTable>

    <div class="pagination-container">
      <ElPagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <div class="my-course-container">
      <h2>我的排课管理</h2>
      <ElTable :data="scheduleData" style="width: 100%" v-loading="scheduleLoading">
        <ElTableColumn prop="className" label="班级名称" width="180" />
        <ElTableColumn prop="courseName" label="课程名称" width="180" />
        <ElTableColumn label="上课信息" width="400">
          <template #default="scope">
            <template v-if="scope && scope.row">
              <div>{{ scope.row.startWeek }}-{{ scope.row.endWeek }}周</div>
              <div>星期{{ scope.row.day }}</div>
              <div>第{{ scope.row.startTime }}-{{ scope.row.endTime }}节</div>
              <div>上课地点：{{ scope.row.classroom }}</div>
            </template>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <ElButton type="primary" size="small" @click="openEditScheduleDialog(row)">
              编辑
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>

      <div class="pagination-container">
        <ElPagination
            v-model:current-page="schedulePagination.currentPage"
            v-model:page-size="schedulePagination.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="schedulePagination.total"
            @size-change="handleScheduleSizeChange"
            @current-change="handleScheduleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建班级弹窗 -->
    <ElDialog v-model="createClassDialogVisible" title="创建班级" width="500px">
      <ElForm ref="createClassFormRef" :model="createClassForm" label-width="100px">
        <ElFormItem label="班级名称" prop="className">
          <ElInput v-model="createClassForm.className" placeholder="请输入班级名称" />
        </ElFormItem>
        <ElFormItem label="专业选择" prop="majorId">
          <ElSelect v-model="createClassForm.majorId" placeholder="请选择专业" :loading="majorLoading" @change="handleMajorChange">
            <ElOption v-for="major in majorList" :key="major.id" :label="major.majorName" :value="major.id" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="课程选择" prop="courseId">
          <ElSelect v-model="createClassForm.courseId" placeholder="请选择课程" :loading="classCourseLoading">
            <ElOption v-for="course in classCourseList" :key="course.id" :label="course.courseName" :value="course.id" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="班级人数" prop="number">
          <ElInput v-model="createClassForm.number" type="number" placeholder="请输入班级人数" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="createClassDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="createClass">确定</ElButton>
      </template>
    </ElDialog>


    <!-- 排课弹窗 -->
    <ElDialog v-model="scheduleDialogVisible" title="排课" width="600px">
      <ElForm ref="scheduleFormRef" :model="scheduleForm" label-width="120px">
        <!-- 课程信息从班级获取，不再需要手动选择 -->
        <ElFormItem label="开始周" prop="startWeek">
          <ElInput v-model="scheduleForm.startWeek" type="number" placeholder="请输入开始周" />
        </ElFormItem>
        <ElFormItem label="结束周" prop="endWeek">
          <ElInput v-model="scheduleForm.endWeek" type="number" placeholder="请输入结束周" />
        </ElFormItem>
        <ElFormItem label="星期" prop="day">
          <ElInput v-model="scheduleForm.day" type="number" placeholder="请输入星期(1-7)" />
        </ElFormItem>
        <ElFormItem label="开始节次" prop="startTime">
          <ElInput v-model="scheduleForm.startTime" type="number" placeholder="请输入开始节次" />
        </ElFormItem>
        <ElFormItem label="结束节次" prop="endTime">
          <ElInput v-model="scheduleForm.endTime" type="number" placeholder="请输入结束节次" />
        </ElFormItem>
        <ElFormItem label="教室" prop="classroom">
          <ElInput v-model="scheduleForm.classroom" placeholder="请输入教室" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="scheduleDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submitSchedule">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import auth from '../../../utils/auth'
import request from '../../../api/request'
import scheduleApi from '../../../api/schedule.js'

export default {
  name: 'MyCourse',
  components: {},
  data() {
    return {
      // 定义班级数据
      classData: [],
      // 定义排课数据
      scheduleData: [],
      // 分页数据
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      // 排课分页数据
      schedulePagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      // 创建班级表单数据
      createClassForm: {
        className: '',
        majorId: '',
        courseId: '',
        number: ''
      },
      // 排课表单数据
      scheduleForm: {
        id: '',
        classId: '',
        courseId: '',
        startWeek: '',
        endWeek: '',
        day: '',
        startTime: '',
        endTime: '',
        classroom: ''
      },
      isEditMode: false,
      // 课程列表（排课用）
      scheduleCourseList: [],
      // 专业列表
      majorList: [],
      // 根据专业ID获取的课程列表（创建班级用）
      classCourseList: [],
      // 课程加载状态（创建班级用）
      classCourseLoading: false,
      // 加载状态
      loading: false,
      courseLoading: false,
      majorLoading: false,
      scheduleLoading: false,
      // 弹窗控制
      createClassDialogVisible: false,
      scheduleDialogVisible: false,
      // 图标
      Plus
    }
  },
  mounted() {
    this.getClassData()
    this.getScheduleData()
  },
  methods: {

    openEditScheduleDialog(row) {
      // 设置为编辑模式
      this.isEditMode = true
      // 填充排课表单数据
      this.scheduleForm = {
        id: row.id,
        classId: row.classId,
        courseId: row.courseId,
        startWeek: row.startWeek,
        endWeek: row.endWeek,
        day: row.day,
        startTime: row.startTime,
        endTime: row.endTime,
        classroom: row.classroom
      }

      // 获取课程列表
      this.getAllCourses()
      this.scheduleDialogVisible = true
    },
    
    // 当专业选择变化时触发 - 移除重复定义
    
    
    // 获取排课数据
    async getScheduleData() {
      this.scheduleLoading = true
      try {
        // 需要获取当前登录用户的用户名，这里假设auth工具可以获取到用户名
        // 如果auth中没有直接获取用户名的方法，可能需要调整获取方式
        const teacherName = auth.getUserName() || ''

        const response = await scheduleApi.getSchedulePage(
            this.schedulePagination.currentPage,
            this.schedulePagination.pageSize,
            '',
            '',
            teacherName  // 传递用户名字符串给后端
        )

        if (response && response.code === 200) {
          // 由于后端已经根据教师名称筛选，前端可以直接使用返回的数据
          this.scheduleData = response.data.records || []
          // 使用后端返回的总记录数
          this.schedulePagination.total = response.data.total || 0
        } else {
          console.error('获取排课数据失败:', response?.msg || '未知错误')
        }
      } catch (error) {
        console.error('请求排课数据时发生错误:', error)
      } finally {
        this.scheduleLoading = false
      }
    },
    // 排课分页变化时触发
    handleScheduleCurrentChange(currentPage) {
      this.schedulePagination.currentPage = currentPage
      this.getScheduleData()
    },

    // 排课每页条数变化时触发
    handleScheduleSizeChange(pageSize) {
      this.schedulePagination.pageSize = pageSize
      this.schedulePagination.currentPage = 1 // 重置为第一页
      this.getScheduleData()
    },

    async deleteClass(classId, className) {
      try {
        // 弹出确认对话框
        await this.$confirm(`确定要删除班级"${className}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 直接使用DELETE请求，通过params传递参数
        const response = await request.delete('/class/delete', {
          params: { classId }
        })

        if (response && response.code === 200) {
          this.$alert('删除班级成功', '提示', {
            confirmButtonText: '确定'
          })
          this.getClassData() // 重新加载班级数据
          this.getScheduleData()
        } else {
          this.$alert(response.msg || '删除班级失败', '提示', {
            confirmButtonText: '确定'
          })
        }
      } catch (error) {
        // 如果用户取消了确认对话框，也会进入catch，这里需要判断
        if (error === 'cancel') {
          return
        }

        console.error('删除班级失败:', error)
        if (error.isForbidden) {
          this.$alert('权限不足或会话已过期，请检查登录状态', '提示', {
            confirmButtonText: '确定'
          })
        } else {
          this.$alert('删除班级失败，请重试', '提示', {
            confirmButtonText: '确定'
          })
        }
      }
    },

    // 创建班级
    async createClass() {
      if (!this.createClassForm.className || !this.createClassForm.majorId || !this.createClassForm.courseId || !this.createClassForm.number) {
        this.$alert('班级名称、专业、课程和人数不能为空', '提示', {
          confirmButtonText: '确定'
        })
        return
      }

      try {
        const teacherId = auth.getUserId()
        if (!teacherId) {
          this.$alert('无法获取教师ID，请重新登录', '提示', {
            confirmButtonText: '确定'
          })
          return
        }

        // 创建URLSearchParams对象来提交表单格式数据
        const params = new URLSearchParams()
        params.append('teacherId', teacherId)
        params.append('className', this.createClassForm.className)
        params.append('majorId', this.createClassForm.majorId)
        params.append('courseId', this.createClassForm.courseId)
        params.append('number', this.createClassForm.number)

        console.log('提交创建班级数据(表单格式):', params.toString())
        const response = await request.post('/class/create', params)

        if (response && response.code === 200) {
          this.$alert('创建班级成功', '提示', {
            confirmButtonText: '确定'
          })
          this.createClassDialogVisible = false
          this.getClassData() // 重新加载班级数据
        } else {
          this.$alert(response.msg || '创建班级失败', '提示', {
            confirmButtonText: '确定'
          })
        }
      } catch (error) {
        console.error('创建班级失败:', error)
        // 捕获403错误但不触发重定向
        if (error.response && error.response.status === 403) {
          this.$alert('权限不足或会话已过期，请检查登录状态', '提示', {
            confirmButtonText: '确定'
          })
          // 不执行auth.removeToken()和window.location.href = '/login'
        } else {
          this.$alert('创建班级失败，请重试', '提示', {
            confirmButtonText: '确定'
          })
        }
      }
    },

    // 获取班级数据
    async getClassData() {
      this.loading = true
      try {
        const teacherId = auth.getUserId()
        const response = await request.get('/class/pageAll', {
          params: {
            teacherId: teacherId,
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
          }
        })

        if (response && response.code === 200) {
          this.classData = response.data.records || []
          this.pagination.total = response.data.total || 0
        } else {
          console.error('获取班级数据失败:', response?.msg || '未知错误')
        }
      } catch (error) {
        console.error('请求班级数据时发生错误:', error)
      } finally {
        this.loading = false
      }
    },

    // 获取所有课程（排课用）
    async getAllCourses() {
      this.courseLoading = true
      try {
        const response = await request.get('/course/selectAll')

        if (response && response.code === 200) {
          this.scheduleCourseList = response.data || []
        } else {
          console.error('获取课程数据失败:', response?.msg || '未知错误')
        }
      } catch (error) {
        console.error('请求课程数据时发生错误:', error)
      } finally {
        this.courseLoading = false
      }
    },
    
    // 专业选择变化时触发
    handleMajorChange(majorId) {
      // 重置课程选择
      this.createClassForm.courseId = ''
      // 根据选择的专业ID获取课程列表
      this.getCoursesByMajorId(majorId)
    },

    // 根据专业ID获取课程列表（创建班级用）
    async getCoursesByMajorId(majorId) {
      if (!majorId) {
        this.classCourseList = []
        return
      }
      
      this.classCourseLoading = true
      try {
        const response = await request.get('/major/selectByMajorId', {
          params: { majorId }
        })
        
        if (response && response.code === 200) {
          this.classCourseList = response.data || []
        } else {
          console.error('获取课程数据失败:', response?.msg || '未知错误')
          this.classCourseList = []
        }
      } catch (error) {
        console.error('请求课程数据时发生错误:', error)
        this.classCourseList = []
      } finally {
        this.classCourseLoading = false
      }
    },

    // 获取所有专业 - 添加详细日志以便调试
    async getAllMajors() {
      console.log('开始获取专业数据...')
      this.majorLoading = true
      try {
        const response = await request.get('/major/list')

        console.log('API响应:', response)

        if (response && response.code === 200) {
          this.majorList = response.data || []
        } else {
          this.$alert(`获取专业数据失败: ${response?.msg || '未知错误'}`, '提示', {
            confirmButtonText: '确定'
          })
        }
      } catch (error) {
        this.$alert(`请求专业数据失败: ${error.message || '网络错误'}`, '提示', {
          confirmButtonText: '确定'
        })
      } finally {
        this.majorLoading = false
        console.log('获取专业数据完成，当前majorList:', this.majorList)
      }
    },

    // 打开排课弹窗
    openScheduleDialog(row) {
      // 设置为创建模式
      this.isEditMode = false
      // 重置排课表单，直接使用班级的courseId
      this.scheduleForm = {
        id: '',
        classId: row.id,
        courseId: row.courseId || '', // 直接使用班级的courseId
        startWeek: '',
        endWeek: '',
        day: '',
        startTime: '',
        endTime: '',
        classroom: ''
      }

      // 不再需要获取课程列表
      this.scheduleDialogVisible = true
    },

    // 提交排课
    async submitSchedule() {
      // 检查courseId是否存在（应该从班级数据获取）
      if (!this.scheduleForm.courseId) {
        this.$alert('班级课程信息不存在，无法排课', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      
      // 检查其他必填字段
      if (!this.scheduleForm.startWeek || !this.scheduleForm.endWeek ||
          !this.scheduleForm.day || !this.scheduleForm.startTime || !this.scheduleForm.endTime ||
          !this.scheduleForm.classroom) {
        this.$alert('请填写完整的排课信息', '提示', {
          confirmButtonText: '确定'
        })
        return
      }

      if (parseInt(this.scheduleForm.startWeek) > parseInt(this.scheduleForm.endWeek)) {
        this.$alert('开始周不能大于结束周', '提示', {
          confirmButtonText: '确定'
        })
        return
      }

      if (parseInt(this.scheduleForm.startTime) >= parseInt(this.scheduleForm.endTime)) {
        this.$alert('开始节次必须小于结束节次', '提示', {
          confirmButtonText: '确定'
        })
        return
      }

      if (parseInt(this.scheduleForm.day) < 1 || parseInt(this.scheduleForm.day) > 7) {
        this.$alert('星期必须在1-7之间', '提示', {
          confirmButtonText: '确定'
        })
        return
      }

      try {
        const teacherId = auth.getUserId()
        const scheduleData = {
          ...this.scheduleForm,
          teacherId
        }

        let response
        if (this.isEditMode) {
          // 编辑模式，调用更新API
          response = await scheduleApi.updateSchedule(scheduleData)
        } else {
          // 创建模式，调用创建API
          response = await request.post('/schedule/create', scheduleData)
        }

        if (response && response.code === 200) {
          this.$alert(this.isEditMode ? '排课更新成功' : '排课成功', '提示', {
            confirmButtonText: '确定'
          })
          this.scheduleDialogVisible = false
          this.getScheduleData()
        } else {
          this.$alert(response.msg || (this.isEditMode ? '排课更新失败' : '排课失败'), '提示', {
            confirmButtonText: '确定'
          })
        }
      } catch (error) {
        console.error(this.isEditMode ? '排课更新失败:' : '排课失败:', error)
        this.$alert(this.isEditMode ? '排课更新失败，请重试' : '排课失败，请重试', '提示', {
          confirmButtonText: '确定'
        })
      }
    },

    // 分页变化时触发
    handleCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage
      this.getClassData()
    },

    // 每页条数变化时触发
    handleSizeChange(pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.currentPage = 1 // 重置为第一页
      this.getClassData()
    },
  },
  watch: {
    // 监听创建班级弹窗的显示状态，当显示时加载专业列表
    createClassDialogVisible(newValue) {
      if (newValue) {
        console.log('弹窗显示，准备加载专业数据')
        this.getAllMajors()
      }
    }
  }
}
</script>

<style scoped>
.my-course-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>